import React, { Component } from 'react';
import styles from './home.module.less';
import { inject, observer } from 'mobx-react';
import { Tag, Skeleton, Button, Radio } from 'antd'; // ...
import { userService, demoService } from '@server/index';
import { withRouter, RouteComponentProps } from 'react-router-dom';
import ListStatus from '@components/list-status';
import Login from '@components/login';
import { theme } from '@theme/index';
import { language, Intl } from '@language/index';

/**
 * 简单的写法，会多一次数据请求
 */

interface HomeProps extends RouteComponentProps {
  // ...
}

interface HomeStates {
  list: Array<any>;
  captcha: string;
}

// ssr 配置
// console.log(process.env.NODE_ENV);

// @ts-ignore
@withRouter
@inject('user')
@observer
class Home extends Component<HomeProps, HomeStates> {

  // 服务端注入数据到props
  static injectSSRData = async () => {
    // console.warn('ajax异步加载数据XXX', routeParams);
    const [res] = await demoService.getTemplates();
    return { ssrRes: res.data };
  };

  constructor(props) {
    super(props);
    this.state = {
      list: props.ssrRes,
      captcha: ''
    };
  }

  componentDidMount() {
    Home.injectSSRData().then(res => {
      console.log('ssrRes.data', res);
      this.setState({ list: res.ssrRes });
    });
    // userService.getCaptcha()
  }

  handleSubmit = async values => {
    // Toast.info('表单已提交');
    const [res] = await userService.login(values);
    console.log(values, res);
    if (res) {
      await userService.getUserDetail();
      this.props.history.push('/manage');
    }
  };

  render() {
    return (
      <>
        <div className={styles.home}>
          <div>
            <h1>SSR</h1>
            <Intl name="Language" />
            <Radio.Group defaultValue="light" onChange={e => {
              theme.setTheme(e.target.value);
            }}>
              <Radio.Button value="dark">dark</Radio.Button>
              <Radio.Button value="light">light</Radio.Button>
            </Radio.Group>
            <Radio.Group defaultValue={language.getLanguage()} onChange={e => {
              language.setLanguage(e.target.value);
            }}>
              <Radio.Button value="zh-CN">中文</Radio.Button>
              <Radio.Button value="en-US">En</Radio.Button>
            </Radio.Group>
            <div>
              <ListStatus data={this.state.list}>
                <Skeleton active style={{ width: 240 }} loading={!this.state.list}>
                  {this.state.list?.map(d => {
                    return (
                      <Tag style={{ margin: 5 }} key={d.id}>
                        {d.name}
                      </Tag>
                    );
                  })}
                </Skeleton>
              </ListStatus>
            </div>
          </div>
        </div>
        <div className={styles.home}>
          <Login>
            <Button type="primary">登录</Button>
          </Login>
        </div>
      </>
    );
  }
}

export default Home;
